package com.zhuiyun.project.api.system.dept.controller;


import com.zhuiyun.project.annotation.OptLog;
import com.zhuiyun.project.api.system.dept.entity.TenantDept;
import com.zhuiyun.project.api.system.dept.service.ISysDeptService;
import com.zhuiyun.project.common.constant.UserConstants;
import com.zhuiyun.project.common.controller.BaseController;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.utils.StringUtils;
import com.zhuiyun.project.utils.constants.CommonConstants;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 部门信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController
{
    @Autowired
    private ISysDeptService deptService;

    /**
     * 获取部门列表
     */
    @GetMapping("/list")
    @ApiOperation(value = "获取部门列表")
    @OptLog(modular = "部门管理", type = CommonConstants.SELECT, describe = "查询部门列表")
    public CommonResult list(TenantDept dept)
    {
        List<TenantDept> depts = deptService.selectDeptList(dept);
        return CommonResult.ok(depts);
    }

    /**
     * 查询部门列表（排除节点）
     */
    @GetMapping("/list/exclude/{deptId}")
    @ApiOperation(value = "查询部门列表")
    @OptLog(modular = "部门管理", type = CommonConstants.SELECT, describe = "查询部门列表")
    public CommonResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId)
    {
        List<TenantDept> depts = deptService.selectDeptList(new TenantDept());
        depts.removeIf(d -> d.getDeptId().intValue() == deptId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""));
        return CommonResult.ok(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @GetMapping(value = "/{deptId}")
    public CommonResult getInfo(@PathVariable Long deptId)
    {
        deptService.checkDeptDataScope(deptId);
        return CommonResult.ok(deptService.selectDeptById(deptId));
    }

    /**
     * 新增部门
     */
    @OptLog(modular = "部门管理", type = CommonConstants.ADD, describe = "添加部门")
    @PostMapping
    public CommonResult add(@Validated @RequestBody TenantDept dept)
    {
        if (!deptService.checkDeptNameUnique(dept))
        {
            return CommonResult.error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(getUsername());
        return CommonResult.ok(deptService.insertDept(dept));
    }

    /**
     * 修改部门
     */
    @OptLog(modular = "部门管理", type = CommonConstants.UPDATE, describe = "修改部门列表")
    @PutMapping
    public CommonResult edit(@Validated @RequestBody TenantDept dept)
    {
        Long deptId = dept.getDeptId();
        deptService.checkDeptDataScope(deptId);
        if (!deptService.checkDeptNameUnique(dept))
        {
            return CommonResult.error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        else if (dept.getParentId().equals(deptId))
        {
            return CommonResult.error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0)
        {
            return CommonResult.error("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(getUsername());
        return CommonResult.ok(deptService.updateDept(dept));
    }

    /**
     * 删除部门
     */
    @OptLog(modular = "部门管理", type = CommonConstants.SELECT, describe = "删除部门列表")
    @DeleteMapping("/{deptId}")
    public CommonResult remove(@PathVariable Long deptId)
    {
        if (deptService.hasChildByDeptId(deptId))
        {
            return CommonResult.error("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId))
        {
            return CommonResult.error("部门存在用户,不允许删除");
        }
        deptService.checkDeptDataScope(deptId);
        return CommonResult.ok(deptService.deleteDeptById(deptId));
    }
}
